<template>
  <div class="order-apply-invoice">
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, watch, nextTick, ref, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

interface ChartConfig {
  xAxisData?: string[]
  yAxisNormalDataBar?: number[]
  yAxisOverDataBar?: number[]
}

const props = defineProps<{
  config: ChartConfig
}>()

const emits = defineEmits<{
  (e: 'barClick', params: any): void
}>()
const chartInstance = ref<echarts.ECharts | null>(null)
const chartContainer = ref<HTMLElement | null>(null)

const getChartOption = () => {
  const { xAxisData = [], yAxisNormalDataBar = [], yAxisOverDataBar = [] } = props.config

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      right: '50px',
      top: '30px',
      selectedMode: false,
      data: ['正常待还数量', '超期待还箱数量']
    },
    grid: {
      left: '3%',
      right: '4%',
      containLabel: true
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}'
      }
    },
    xAxis: {
      type: 'category',
      data: xAxisData
    },
    series: [
      {
        name: '正常待还数量',
        type: 'bar',
        stack: 'total',
        barWidth: '60%',
        label: {
          show: true,
          position: 'inside',
          formatter: (params: any) => params.value > 0 ? `${params.value}个` : ''
        },
        data: yAxisNormalDataBar
      },
      {
        name: '超期待还箱数量',
        type: 'bar',
        stack: 'total',
        barWidth: '60%',
        label: {
          show: true,
          position: 'inside',
          formatter: (params: any) => params.value > 0 ? `${params.value}个` : ''
        },
        data: yAxisOverDataBar
      }
    ]
  }
}

const initChart = () => {
  if (!chartContainer.value) return

  nextTick(() => {
    if (!chartInstance.value) {
      chartInstance.value = echarts.init(chartContainer.value)
       // 添加点击事件监听
        chartInstance.value.on('click', 'series.bar', (params: any) => {
          emits('barClick', params)
        })
    }
    chartInstance.value.setOption(getChartOption())
  })
}



watch(() => props.config, () => {
    initChart()
}, { deep: true })

onMounted(() => {
    initChart()
})

onBeforeUnmount(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose()
    chartInstance.value = null
  }
})
</script>

<style lang="scss" scoped>
.order-apply-invoice {
  width: 100%;
  height: 100%;
  
  .chart-container {
    width: 100%;
    height: 400px;
  }
}
</style>